// pages/car_list/car_list.js
var api = require('../../api/api');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    curindex:0,
    list:[],
    serviceId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      serviceId:options.service_id
    })
  },
  getUserCar(){
    api.get('/user/cars').then(res=>{
      this.setData({
        list:res.items
      })
    })
  },
  //选择车辆
  select_car(e){
    if(!this.data.serviceId){
      return false;
    }
    let that = this;
    const index=e.currentTarget.dataset.index;
    that.setData({
      curindex:index
    })
    let location = wx.getStorageSync('Location')
    api.post('/appoint/servicePrice',{
      service_id:this.data.serviceId,
      car_id:this.data.list[index].id
    }).then(res=>{
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1]; //当前页面
      var prevPage = pages[pages.length - 2];
      prevPage.setData({
        'selectedService.price':res.price,
        selectCar:that.data.list[index]
      })
      console.log('选择车',that.data.list[index],index)
      wx.navigateBack({
        delta: 1,
      })
    })
    return false;

   
  },
  //新增车辆
  click_add_car(){
    wx.navigateTo({
      url: '../add_car/add_car',
    })
  },
  delCar(e){
    let index = e.currentTarget.dataset.index;
    let id = this.data.list[index].id;
    api.post('/user/deleteCar/'+id).then(res=>{
      wx.showToast({
        title: '删除成功',
        icon:'none'
      })
      let lists = this.data.list;
      lists.splice(index,1);
      this.setData({
        list:lists
      })
    })
  },
  editCar(e){
    let index = e.currentTarget.dataset.index;
    let id = this.data.list[index].id;
    wx.setStorageSync('editCar', this.data.list[index])
    wx.navigateTo({
      url: '/pages/add_car/add_car?id='+id,
    })
  },
  saveDefaultCar(e){
    let index = e.currentTarget.dataset.index;
    let id = this.data.list[index].id;
    api.post('/user/saveDefaultCar/'+id).then(res=>{
      let lists = this.data.list;
      lists.map((item,key)=>{
        if(index == key){
          item.is_default = true;
          wx.setStorageSync('defaultCar', item)
        }else{
          item.is_default = false;
        }
      })
      this.setData({
        list:lists
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getUserCar();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})